package com.demo.core.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.demo.base.cons.SessionKeyConstant;
import com.demo.base.util.RequestContextHolderUtil;

public class UserAuthInterceptor extends HandlerInterceptorAdapter {


	// 不需要登录即可访问的URI资源
	private List<String> excludedUris;

	public void setExcludedUris(List<String> excludedUris) {
		this.excludedUris = excludedUris;
	}

	/**
	 * 检查用户是否登录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String requestURI = request.getRequestURI();
		String sid = request.getParameter("sid");
		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		if (!StringUtils.isEmpty(requestURI)) {
			//如果是网站上的不拦截
			if(requestURI.startsWith("/web/")){
				return true;
			}else{
				Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) RequestContextHolderUtil.getSession().getAttribute(SessionKeyConstant.SESSION_CONTEXT);
				if (map == null) {
					map = new HashMap<String, Map<String, Object>>();
				}
				Map<String, Object> m = null;
				if (m == null) {
					m = new HashMap<String, Object>();
				}
				if (!StringUtils.isBlank(sid)) {
					/* 对已经登录的访问不做处理 */
					if (m.get(sid) != null) {
						return true;
					}
					/* AJAX提交访问不做处理 在程序里面判断即可 */
					if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
						return true;
					}
					

				} else {
					for (final String uri : excludedUris) { // 排除不需要登录即可访问的URI资源
						if (requestURI.equals(uri)) {
							return true;
						} else if (requestURI.startsWith(uri)) {// 以XXX开头的URI资源
							return true;
							}
						}
					}
				}	
			} else {
				return true;
			}

		return false;
	}
}
